package com.zhiwei.gateway.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zhiwei.common.constant.ErrorEnum;
import com.zhiwei.common.constant.ResultResponseMsg;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * function spring security登陆认证失败处理器
 * author zhiwei.yang
 * time 2020-2-27-15:29
 */
@Component
public class MyExceptionMappingAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
            throws IOException, ServletException {
        response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());
        ResultResponseMsg resultResponseMsg = ResultResponseMsg.buildResultMsg(ErrorEnum.HTTP_LOGIN, null);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.getWriter().println(JSON.toJSONString(resultResponseMsg, SerializerFeature.WriteMapNullValue));
        response.getWriter().flush();
        response.getWriter().close();
    }
}